<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增租赁出库记录')" />
    <th:block th:include="include :: datetimepicker-css" />
    <style>
        .item-list {
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        .item-card {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .item-card:hover {
            border-color: #1ab394;
            background-color: #fafafa;
        }
        .item-card.selected {
            border-color: #1ab394;
            background-color: #e8f4ff;
        }
        .item-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            margin-right: 10px;
            border-radius: 4px;
        }
        .item-info {
            flex: 1;
        }
        .item-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .item-details {
            font-size: 12px;
            color: #666;
        }
        .item-quantity {
            color: #ff6a6a;
            font-weight: bold;
        }
        .disabled-section {
            opacity: 0.5;
            pointer-events: none;
        }
    </style>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-lease-add">
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">关联订单号：</label>
                <div class="col-sm-8">
                    <select name="orderId" id="orderId" class="form-control" required>
                        <option value="">请选择</option>
                        <option th:each="order : ${orderList}" th:value="${order.id}" th:text="${order.id}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">出库物品：</label>
                <div class="col-sm-8">
                    <!-- 物品展示容器 -->
                    <div id="itemContainer" class="item-list">
                        <div class="help-block text-center" id="itemMessage">请先选择订单号</div>
                        <!-- 物品将通过JS动态生成 -->
                    </div>
                    <input type="hidden" name="itemId" id="selectedItemId">
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">本次出库数量：</label>
                <div class="col-sm-8">
                    <input name="leaseQuantity" id="leaseQuantity" class="form-control" type="text" required>
                    <div class="help-block">可选数量：<span id="maxQuantity">0</span></div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">实际出库时间：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input name="leaseTime" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">状态：</label>
                <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dict.getType('lease_status')}">
                        <input type="radio" th:id="${'leaseStatus_' + dict.dictCode}" name="leaseStatus" th:value="${dict.dictValue}" th:checked="${dict.default}" required>
                        <label th:for="${'leaseStatus_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var prefix = ctx + "system/lease";
    $("#form-lease-add").validate({
        focusCleanup: true,
        rules: {
            itemId: { required: true },
            leaseQuantity: {
                required: true,
                digits: true,
                min: 1,
                max: function() {
                    return parseInt($('#maxQuantity').text()) || 0;
                }
            }
        },
        messages: {
            itemId: { required: "请选择出库物品" },
            leaseQuantity: {
                required: "请输入出库数量",
                digits: "请输入有效数字",
                min: "出库数量至少为1",
                max: "出库数量不能超过可用数量"
            }
        }
    });

    function submitHandler() {
        if ($.validate.form()) {
            // 打印提交的表单内容
            console.log($('#form-lease-add').serialize());
            $.operate.save(prefix + "/add", $('#form-lease-add').serialize());
        }
    }

    $("input[name='leaseTime']").datetimepicker({
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true
    });

    // 新增的JavaScript代码
    $(document).ready(function() {
        // 监听订单号下拉框变化
        $('#orderId').change(function() {
            var orderId = $(this).val();
            var $itemContainer = $('#itemContainer');
            var $itemMessage = $('#itemMessage');
            var $leaseQuantity = $('#leaseQuantity');

            // 清空物品容器
            $itemContainer.find('.item-card').remove();
            $('#selectedItemId').val('');
            $leaseQuantity.val('');
            $('#maxQuantity').text('0');
            $leaseQuantity.prop('disabled', false);

            // 重置验证
            $("#form-lease-add").validate().resetForm();

            if (orderId) {
                $itemContainer.removeClass('disabled-section');

                // 显示加载提示
                $itemMessage.text('正在加载订单物品...').show();

                // 调用后台接口获取订单下的物品
                $.ajax({
                    url: ctx + 'system/order/queryOrderItems',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({orderId: orderId}),
                    success: function(result) {
                        $itemMessage.hide();

                        if (result.code === 0 && result.data && result.data.length > 0) {
                            // 遍历物品列表，构建商品项
                            $.each(result.data, function(index, item) {
                                var itemHtml = `
                                        <div class="item-card d-flex" data-item-id="${item.itemId}" data-max-quantity="${item.quantity}">
                                            ${item.imgUrl ?
                                    `<img src="${item.imgUrl}" alt="${item.itemName}" class="item-image">` :
                                    `<div class="item-image bg-light d-flex align-items-center justify-content-center">
                                                    <i class="fa fa-box-open" style="font-size: 24px;"></i>
                                                </div>`
                                }
                                            <div class="item-info">
                                                <div class="item-name">${item.itemName || '未知物品'}</div>
                                                <div class="item-details">
                                                    <span>数量: <span class="item-quantity">${item.quantity}</span></span> |
                                                    <span>日租金: ¥${item.dailyRate}</span> |
                                                    <span>租赁天数: ${item.days}天</span>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                                $itemContainer.append(itemHtml);
                            });
                        } else {
                            $itemMessage.text('该订单下没有物品').show();
                        }
                    },
                    error: function() {
                        $itemMessage.text('获取订单物品失败，请重试').show();
                    }
                });
            } else {
                $itemContainer.addClass('disabled-section');
                $itemMessage.text('请先选择订单号').show();
            }
        });

        // 监听物品选择事件
        $(document).on('click', '.item-card', function() {
            $('.item-card').removeClass('selected');
            $(this).addClass('selected');

            var itemId = $(this).data('item-id');
            console.log("itemId===>" + itemId);

            var maxQuantity = parseInt($(this).data('max-quantity') || 0);

            var val = $('#selectedItemId').val(itemId);
            console.log("itemId form ====>" + val);
            $('#maxQuantity').text(maxQuantity);
            $('#leaseQuantity').attr('placeholder', '最大数量: ' + maxQuantity);
            if (!itemId) return; // 跳过无效值

            $('#selectedItemId').val(itemId); // 确保赋值为数字字符串
            // 设置数量输入框最大值
            $("#form-lease-add").find('input[name="leaseQuantity"]').rules('remove', 'max');
            $("#form-lease-add").find('input[name="leaseQuantity"]').rules('add', {
                max: maxQuantity
            });
        });

        // 初始状态
        $('#itemContainer').addClass('disabled-section');
    });
</script>
</body>
</html>